package cn.jdy.plugins.service;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import cn.jdy.authority.entity.Organ;
import cn.jdy.authority.service.OrganService;
import cn.jdy.authority.service.UserService;
import cn.jdy.common.util.XMLUtil;
import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.ApplyCash;
import cn.jdy.plugins.entity.Line;
import cn.jdy.plugins.entity.Live;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.entity.WatchUser;
import cn.jdy.plugins.wap.util.ChatUtil;
import cn.jdy.plugins.wap.util.HttpUtils;
import cn.jdy.plugins.wap.util.RedPacketUtil;

/**
 * @author lutan
 * @title : 直播操作实现
 */
@Service
public class ApplyCashService extends BaseDao<ApplyCash> {
	@Autowired
	private WatchUserService watchUserService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private OrganService organService;
	@Autowired
	private LiveService liveService;
	@Autowired
	protected HttpServletRequest request;
	//企业付款接口地址
	private static final String TRANSFERS_PAY = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; 
	
	public Map<String, Object> applyBySys() {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		/*BaseLog.e(this.getClass(), "处理用户提现请求->userOpenId:"+userOpenId+",userNickName:"+userNickName+",liveId:"+liveId
				+",applyCash:"+applyCash+",appid:"+appid+",mchid="+mchid+",apikey:"+apikey);*/
		String result = "提现成功!";
		String statusCode = "2";  //1-成功 2-失败
		List<ApplyCash> alist=this.find("status","1");
		
		for (ApplyCash cash : alist) {
			
	
		String trade_no = ChatUtil.create_timestamp(); //商户订单号
		try {
			//获取当前看用户信息
			Member user = memberService.find(cash.getId());
			if(null != user){
    			Organ organ = organService.find("40288119669feb25016717b91a6a0001");

				SortedMap<Object, Object> parm = new TreeMap<Object, Object>();
				parm.put("mch_appid", organ.getAppId()); //公众账号appid
	            parm.put("mchid", organ.getMchid()); //商户号
	            parm.put("nonce_str", RedPacketUtil.pay_nonce_str()); //随机字符串
	            parm.put("partner_trade_no", trade_no); //商户订单号
	            parm.put("openid", user.getOpenId()); //用户openid  
	            parm.put("check_name", "NO_CHECK"); //校验用户姓名选项:NO_CHECK-不校验真实姓名 OPTION_CHECK,FORCE_CHECK-强校验真实姓名
	            //parm.put("re_user_name", "安迪"); //check_name设置为FORCE_CHECK或OPTION_CHECK，则必填
//	            parm.put("amount", "100"); //转账金额,单位为分  单笔最小金额默认为1元
	            parm.put("amount",  RedPacketUtil.get_total_fee(cash.getTotal())); //转账金额,单位为分  单笔最小金额默认为1元
	            parm.put("desc", "提现"); //企业付款描述信息
	            parm.put("spbill_create_ip", RedPacketUtil.getHostAddress()); //服务器Ip地址
	            String sign = RedPacketUtil.createSign("UTF-8", parm, organ.getApikey());
	            parm.put("sign", sign);
				
	            String requestXML = RedPacketUtil.getRequestXml(parm);
//		  	    String xmlStr = WxHttpUtil.postData(TRANSFERS_PAY, requestXML);
	         
	    			// 获取线路信息
	         
	    			// 获取机构信息中的appid，appsecret
	    		//	Organ organ = organService.find("bab3df555dcfad6f015dd049e0d90000");
	            	if(null != organ){
	            		    String path = request.getSession().getServletContext().getRealPath("/");
	            		    String currentPath = new File(path).getParent()+organ.getDiploma();
	            		 	String xmlStr =  HttpUtils.posts(organ.getMchid(),currentPath,TRANSFERS_PAY,requestXML);
		       		  	    if(xmlStr.indexOf("SUCCESS") != -1) {   
		       		        	  Map<String, String> map = XMLUtil.doXMLParse(xmlStr); 
		       		        	  String result_code = map.get("result_code");
		       		        	  if(StringUtil.isNotEmpty(result_code) && result_code.equals("SUCCESS")){
		       		        		  statusCode = "1"; 
		       		        	  	  String partner_trade_no = map.get("partner_trade_no");  //商户订单号 
		       		        		  String payment_no = map.get("payment_no");      //企业付款成功，返回的微信订单号
		       		        		  String payment_time = map.get("payment_time");  //企业付款成功时间
		       		        		  
		       		        		  user.setKtxmoney(user.getKtxmoney()+cash.getTotal());
		       		        		  //当前余额
		       		        		  double currentMoney =  RedPacketUtil.sub(user.getMoney(), cash.getTotal());
		       		        		  
		       		        	
		       		        		  cash.setStatus("2");
		       		        		  this.update(cash);
		       		   
		       		   
		       		  				  user.setMoney(currentMoney);
		       		  				  user.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
		       		  				  watchUserService.update(user);
		       		        		  
		       		        	  }else{
		       		        		  String err_code_des = map.get("err_code_des");
		       		        		  result = err_code_des;  
		       		        	  }
		       		          }else{
		       		        	  result = "系统繁忙,请稍后再试!";
		       		          }
	            	}else{
	            		result = "获取商户证书信息失败,请稍后重试！";
	            	}
	            	/*   
		  	  if(statusCode.equals("2")){  //失败时
				cash.setOrderNo(trade_no);
					cash.setStatus("3");   //1-申请提现 ，2-成功， 3-失败
					cash.setTotal(user.getTotal());
					cash.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
					applyCashService.save(cash);
				}*/
				
			}else{
				result = "获取用户信息失败,请稍后重试！";
			}
			
			
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "修改异常", e);
			result = "连接失败，请稍后重试！";
		}
		}
		jsonMap.put("result", result);
		return jsonMap;
	} 
	
	/**
	 * 按条件查询
	 * 
	 * @param ApplyCash
	 * @return
	 */
	@Cacheable(value = "cache1", key = "'help_id' + #ApplyCash.id")
	public List<ApplyCash> query(ApplyCash ApplyCash ,String... date) {
		if (ApplyCash == null)
			return super.findAll();
		List<ApplyCash> list = null;

		if (ApplyCash.getiDisplayLength() > 0) {
			list = super.find(createFilter(ApplyCash, date), ApplyCash.getiDisplayStart(),
					ApplyCash.getiDisplayLength());
		} else {
			list = super.find(createFilter(ApplyCash, date));
		}

		return list;
	}

	@Cacheable(value = "cache1", key = "'help_count' + #ApplyCash.id")
	public Long count(ApplyCash ApplyCash) {
		return super.count(createFilter(ApplyCash));
	}

	/**
	 * 拼装条件
	 * 
	 * @param ApplyCash
	 * @param page
	 * @return
	 */
	private DetachedCriteria createFilter(ApplyCash ApplyCash, String... date) {
		DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
		if (!StringUtil.isNullOrEmpty(ApplyCash.getUserNickName())) {
			dc.add(Restrictions.like("userNickName", ApplyCash.getUserNickName(),MatchMode.ANYWHERE));
		}
		if (!StringUtil.isNullOrEmpty(ApplyCash.getStatus())) {
			dc.add(Restrictions.eq("status", ApplyCash.getStatus()));
		}
		if (!StringUtil.isNullOrEmpty(ApplyCash.getUserOpenId())) {
			dc.add(Restrictions.eq("userOpenId", ApplyCash.getUserOpenId()));
		}
		if (date.length > 0 && !StringUtil.isNullOrEmpty(date[0])
				&& !StringUtil.isNullOrEmpty(date[1])) {
			dc.add(Restrictions.between("createTime", date[0], date[1]));
		}
		dc.addOrder(Order.desc("createTime"));
		return dc;
	}
	

	/**
	 * 修改状态
	 * @param id
	 * @param url
	 * @param name
	 */
		public void updatestatus(Long id,String status){
			try {
				String sql="UPDATE applycash SET status=:status WHERE id=:id";
				SQLQuery sqlQuery = em().createSQLQuery(sql);
				sqlQuery.setParameter("status", status);
				sqlQuery.setParameter("id", id);
				sqlQuery.executeUpdate();
			} catch (Exception e) {
				BaseLog.e(this.getClass(), "更新异常", e);
			}
			
		} 
}
